﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows.Media.Imaging;

namespace iMusik
{
    public partial class PhonePage2 : PhoneApplicationPage
    {
        private bool _IsLoadedFavorite;
        private bool _IsLoadedSdCard;
        DispatcherTimer _timer;
        private Point _MouseDownPoint;
        private Point _MouseUpPoint;
        private MEDIA _CurrentMedia;
        private ImageBrush _SongImage;

        public PhonePage2()
        {
            InitializeComponent();

            _IsLoadedFavorite = false;
            _IsLoadedSdCard = false;
            _timer = new DispatcherTimer();
            _timer.Tick += timer_Tick;
            MediaPlayer.MediaStateChanged += _OnMediaStateChanged;
            MediaPlayer.ActiveSongChanged += _OnActiveSongChanged;
            _CurrentMedia = MEDIA.SONG;
            _SongImage = new ImageBrush();
            _SongImage.ImageSource = new BitmapImage(new Uri(@"/Assets/Images/music_icon.png", UriKind.Relative));
        }

        public void LoadFavorite()
        {
            if (!_IsLoadedFavorite)
            {
                List<ItemView> list = new List<ItemView>();
                MediaLibrary library = new MediaLibrary();
                SongCollection songs = library.Songs;
                foreach (Song song in songs)
                {
                    if (song.IsRated)
                        list.Add(new ItemView(song.Name, song.Artist.Name, _SongImage));
                }

                _llsFavorite.ItemsSource = list;
                _IsLoadedFavorite = true;
            }
        }

        public void LoadSdCard()
        {
            if (!_IsLoadedSdCard)
            {
                List<ItemView> list = new List<ItemView>();
                ICollection<MediaSource> mediaSources = MediaSource.GetAvailableMediaSources();
                foreach (MediaSource source in mediaSources)
                {
                    if (source.MediaSourceType == MediaSourceType.WindowsMediaConnect)
                    {
                        MediaLibrary library = new MediaLibrary(source);
                        SongCollection songs = library.Songs;
                        foreach (Song song in songs)
                        {
                            ItemView itv = new ItemView(song.Name, song.Artist.Name, _SongImage);
                            list.Add(itv);
                        }
                    }
                }

                _llsSdCard.ItemsSource = list;
                _IsLoadedSdCard = true;
            }
        }

        public void LoadContent()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SEARCH:
                    _grdSearchControl.Height = 80;
                    _grdSong.Height = 486;

                    _llsSearch.Visibility = System.Windows.Visibility.Visible;

                    _llsFavorite.Visibility = System.Windows.Visibility.Collapsed;
                    _llsSdCard.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case MEDIA.FAVORITE:
                    LoadFavorite();

                    _grdSearchControl.Height = 0;
                    _grdSong.Height = 566;

                    _llsFavorite.Visibility = System.Windows.Visibility.Visible;

                    _llsSearch.Visibility = System.Windows.Visibility.Collapsed;
                    _llsSdCard.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case MEDIA.SDCARD:
                    LoadSdCard();

                    _grdSearchControl.Height = 0;
                    _grdSong.Height = 566;

                    _llsSdCard.Visibility = System.Windows.Visibility.Visible;

                    _llsSearch.Visibility = System.Windows.Visibility.Collapsed;
                    _llsFavorite.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                default:
                    _grdSearchControl.Height = 0;
                    _grdSong.Height = 566;

                    _llsSearch.Visibility = System.Windows.Visibility.Collapsed;
                    _llsFavorite.Visibility = System.Windows.Visibility.Collapsed;
                    _llsSdCard.Visibility = System.Windows.Visibility.Collapsed;
                    break;
            }
        }

        public void LoadInterface()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SEARCH:
                    _txtTile.Text = "Tìm kiếm";
                    break;

                case MEDIA.FAVORITE:
                    _txtTile.Text = "Yêu thích";
                    break;

                case MEDIA.SDCARD:
                    _txtTile.Text = "Thẻ nhớ";
                    break;

                default:
                    _txtTile.Text = "";
                    break;
            }
        }

        private void NextMedia()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SEARCH:
                    _CurrentMedia = MEDIA.FAVORITE;
                    break;
                case MEDIA.FAVORITE:
                    _CurrentMedia = MEDIA.SDCARD;
                    break;
                case MEDIA.SDCARD:
                    _CurrentMedia = MEDIA.SEARCH;
                    break;
                default:
                    _CurrentMedia = MEDIA.SEARCH;
                    break;
            }
            LoadInterface();
            LoadContent();
        }

        private void PrevMedia()
        {
            switch (_CurrentMedia)
            {
                case MEDIA.SEARCH:
                    _CurrentMedia = MEDIA.SDCARD;
                    break;

                case MEDIA.SDCARD:
                    _CurrentMedia = MEDIA.FAVORITE;
                    break;

                default:
                    _CurrentMedia = MEDIA.SEARCH;
                    break;
            }
            LoadInterface();
            LoadContent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string gridName = "";
            try
            {
                gridName = NavigationContext.QueryString["parameter"];
            }
            catch
            { }

            switch (gridName)
            {
                case "_grdSearch":
                    _CurrentMedia = MEDIA.SEARCH;
                    break;
                case "_grdFavorite":
                    _CurrentMedia = MEDIA.FAVORITE;
                    break;
                case "_grdSdCard":
                    _CurrentMedia = MEDIA.SDCARD;
                    break;
                default:
                    _CurrentMedia = MEDIA.SONG;
                    break;
            }
            LoadContent();
            LoadInterface();
        }

        private void lls_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LongListSelector lls = null;
            try
            {
                lls = (sender as LongListSelector);
            }
            catch
            {
                return;
            }
            if (lls == null)
                return;

            if (lls.SelectedItem == null)
                return;

            string songName = "";
            try
            {
                ItemView ivm = (lls.SelectedItem as ItemView);
                songName = ivm._Name.Text;
            }
            catch
            {
                return;
            }

            Song selectedSong = null;
            using (MediaLibrary ml = new MediaLibrary())
            {
                SongCollection songs = ml.Songs;
                foreach (Song song in songs)
                {
                    if (song.Name == songName)
                    {
                        selectedSong = song;
                        break;
                    }
                }
            }
            if (selectedSong != null)
                MediaPlayer.Play(selectedSong);
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (_txtSearch.Text == "")
                MessageBox.Show("Chưa nhập tên bài hát");
            else
            {
                List<ItemView> list = new List<ItemView>();
                using (MediaLibrary ml = new MediaLibrary())
                {
                    SongCollection songs = ml.Songs;
                    foreach (Song song in songs)
                    {
                        try
                        {
                            if (song.Name.ToLower().IndexOf(_txtSearch.Text.ToLower()) >= 0)
                                list.Add(new ItemView(song.Name, song.Artist.Name, _SongImage));
                        }
                        catch
                        { }
                    }
                }
                _llsSearch.ItemsSource = list;
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            _ctrMedia._txtDuration.Text = MediaPlayer.PlayPosition.Duration().ToString(@"mm\:ss");
        }

        private void _OnMediaStateChanged(object sender, EventArgs e)
        {
            switch (MediaPlayer.State)
            {
                case MediaState.Paused:
                    if (_timer.IsEnabled)
                        _timer.Stop();
                    break;
                case MediaState.Playing:
                    if (!_timer.IsEnabled)
                        _timer.Start();
                    break;
                case MediaState.Stopped:
                    if (_timer.IsEnabled)
                        _timer.Stop();
                    break;
            }
        }

        private void _OnActiveSongChanged(object sender, EventArgs e)
        {
            _timer.Interval = new TimeSpan(3333);
            if (!_timer.IsEnabled)
                _timer.Start();
            if (MediaPlayer.Queue.ActiveSong != null)
            {
                _ctrMedia._txtCurrentSong.Text = MediaPlayer.Queue.ActiveSong.Name;
                _ctrMedia.SetPlayButton();
            }
        }

        private void grdSong_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _MouseDownPoint = e.GetPosition(_grdSong);
        }

        private void grdSong_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            _MouseUpPoint = e.GetPosition(_grdSong);
            if (_MouseUpPoint.Y >= _MouseDownPoint.Y - 20 && _MouseUpPoint.Y <= _MouseDownPoint.Y + 20
                && _MouseDownPoint.X > _MouseUpPoint.X + 20)
            {
                NextMedia();
            }
            else if (_MouseUpPoint.Y >= _MouseDownPoint.Y - 20 && _MouseUpPoint.Y <= _MouseDownPoint.Y + 20
                && _MouseDownPoint.X < _MouseUpPoint.X - 20)
            {
                PrevMedia();
            }
        }

        private void btnNextTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NextMedia();
        }

        private void btnPrevTile_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            PrevMedia();
        }
    }
}